<?php
/**
 * Created by PhpStorm.
 * User: rabbibox
 * Date: 2017/7/14
 * Time: 11:35
 */


namespace api\controllers;

use Yii;
use api\models\LoginForm;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\QueryParamAuth;
use yii\filters\RateLimiter;
use yii\helpers\ArrayHelper;
use api\models\user;
use yii\web\IdentityInterface;

class UserController extends  ApiController{

  public $modelClass = 'api\models\user';

  # 行为 添加
  #   验证 ：authenticator
  #   速度控制：rateLimiter
  public function behaviors()
  {
    $behaviors = parent::behaviors();
    $behaviors['authenticator']['optional'] =  [
      'login',
    ];
    return $behaviors;
  }

  public function actionP($token)
  {
    return $token;
  }


  /**
   * 获取用户信息
   */
  public function actionUs ($token)
  {
    //http://api.aa.com/users/us?access_token=fXz-wI5XVc_Kkcyeol40BWjaJgZLiXCL_1500020911
    // 到这一步，token都认为是有效的了
    // 下面只需要实现业务逻辑即可，下面仅仅作为案例，比如你可能需要关联其他表获取用户信息等等
    $user = User::findIdentityByAccessToken($token);
    return [
      'id' => $user->id,
      'username' => $user->username,
      'email' => $user->email,
    ];
  }


  /**
   * 登录
   */
  public function actionLogin()
  {
    //curl.exe  -d "username=admin&password=111111" http://api.aa.com/users/login
    //return fXz-wI5XVc_Kkcyeol40BWjaJgZLiXCL_1500020911
//    var_dump(Yii::$app->request->post());
//    var_dump($_POST);
//    exit;
    $model = new LoginForm;
    $model->setAttributes(Yii::$app->request->getQueryParams());
    if ($user = $model->login()) {
      if ($user instanceof IdentityInterface) {
        return $user->access_token;
      } else {
        return $user->errors;
      }
    } else {
      return $model->errors;
    }
  }



}
